package org.rendao.utils;

import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

import org.rendao.model.CommonSummary;
import org.rendao.model.FusionchartData;
import org.rendao.model.FusionchartDataItem;

public class ReportUtils {

	public static FusionchartData getFusionchartData(List<CommonSummary> data, String caption, String xAxisName, String yAxisName) {

		FusionchartData fcData = new FusionchartData();
		fcData.setCaption(caption);
		fcData.setxAxisName(xAxisName);
		fcData.setyAxisName(yAxisName);
		
		List<FusionchartDataItem> items = new ArrayList<FusionchartDataItem>();
		if(data != null) {
			for(CommonSummary s : data) {
				String label = s.getLabel();
				String value = s.getValue();
				FusionchartDataItem item = new FusionchartDataItem();
				item.setLabel(label);
				item.setValue(value);
				items.add(item);
			}
		}
		fcData.setDataSet(items);

		return fcData;
	}
	
	public static String getFusionchartDataXml(List<CommonSummary> data, String caption, String xAxisName, String yAxisName) {
		FusionchartData fcData = getFusionchartData(data, caption, xAxisName, yAxisName);
		try {
			JAXBContext context = JAXBContext.newInstance(FusionchartData.class, FusionchartDataItem.class);
			Marshaller m = context.createMarshaller();
			m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
			StringWriter sw = new StringWriter();
			m.marshal(fcData, sw);
			return sw.toString();
		} catch (JAXBException e) {
			throw new RuntimeException("Serialize fusionchart data failed");
		}
	}
}
